/**
 * IO函子的问题
 */
import fs from 'fs'
const compose = (f: (...args: any) => any, g: (...args: any) => any) => {
  return value => f(g(value))
}

class IO {
  static of (value) {
    return new IO(() => value)
  }

  _value: (...args: any) => any
  constructor (fn) {
    this._value = fn
  }

  map (fn) {
    return new IO(compose(fn, this._value))
  }
}

let readFile = filename => IO.of(fs.readFileSync(filename, 'utf-8'))
let print = x => IO.of(x).map(x => {
  console.log(x)
  return x
})

// readFile返回一个IO函子，print接收这个IO函子
// cat最终返回的是一个嵌套的IO函子 IO(IO(x))
let cat = compose(print, readFile)

// 函子嵌套时调用不方便
let r = cat('../../package.json')._value()._value()
console.log(r)
